# -*- coding: utf-8 -*-

import base64
import os
import time

import qrcode

from odoo import api, fields, models

# 文件路径
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
IMG_PATH = os.path.join(BASE_PATH, 'static', 'img')


# 访客登记数据模型
class Registration(models.Model):
    _name = 'visiting.registration'
    _description = '访客登记'

    visitor_name = fields.Many2one('res.partner', string='访客名称')

    visitor_time = fields.Datetime(string='探访时间')
    create_time = fields.Datetime(string='创建时间', default=time.strftime('%Y-%m-%d %H:%M:%S'))
    qrcode = fields.Binary(string='二维码')
    complete_visit = fields.Boolean(string='是否完成', default=False)

    # 生成二维码
    def generate_qrcode(self):
        for res in self:
            if not self.qrcode:
                qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4)
                qr.add_data('欢迎来到浙江华光汽车内饰股份有限公司')
                qr.make(fit=True)
                qrcode_file = qr.make_image()

                # 保存地址
                qrcode_file.save(os.path.join(IMG_PATH, f'{res.apple_uid}.png'))
                image = open(os.path.join(IMG_PATH, f'{res.apple_uid}.png'), 'rb').read()

                res.qrcode = base64.encodestring(image)
            else:
                pass

    # 生成访客 UID
    @api.model
    def _create_apple_uid(self):
        apple_uid = time.strftime("%Y%m%d%H%M%S", time.localtime())
        return apple_uid

    apple_uid = fields.Char(string='访客 UID', default=_create_apple_uid)
    state_choice = [('new', '新建'), ('completed', '已完成')]
    state = fields.Selection(state_choice, string='状态', readonly=True, copy=False, tracking=2, default='new')

    # 如果用户完成探访，点击该按钮将可以使得 `complete_visit` 变为 True，状态栏也由（新建 -> 已完成）
    def button_confirm(self):
        return self.write({'complete_visit': True, 'state': 'completed'})
